// 数据库优化配置 - 生产环境最佳实践
import dotenv from 'dotenv';

dotenv.config();

const config = {
  // 应用配置
  app: {
    name: process.env.APP_NAME || 'bike-wholesale-app',
    version: process.env.APP_VERSION || '1.0.0',
    environment: process.env.NODE_ENV || 'development',
    logLevel: process.env.LOG_LEVEL || 'info'
  },

  // 数据库优化配置
  database: {
    // PostgreSQL优化配置
    postgresql: {
      host: process.env.DB_HOST || 'localhost',
      port: parseInt(process.env.DB_PORT) || 5432,
      name: process.env.DB_NAME || 'bike_wholesale',
      user: process.env.DB_USER || 'postgres',
      password: process.env.DB_PASSWORD || 'password',
      
      // 连接池优化
      maxConnections: parseInt(process.env.DB_MAX_CONNECTIONS) || 50,
      minConnections: parseInt(process.env.DB_MIN_CONNECTIONS) || 5,
      idleTimeout: parseInt(process.env.DB_IDLE_TIMEOUT) || 30000,
      connectionTimeout: parseInt(process.env.DB_CONNECTION_TIMEOUT) || 5000,
      
      // 性能优化
      statementTimeout: parseInt(process.env.DB_STATEMENT_TIMEOUT) || 30000,
      queryTimeout: parseInt(process.env.DB_QUERY_TIMEOUT) || 60000,
      
      // SSL配置
      ssl: process.env.DB_SSL === 'true' ? {
        rejectUnauthorized: false,
        ca: process.env.DB_SSL_CA,
        cert: process.env.DB_SSL_CERT,
        key: process.env.DB_SSL_KEY
      } : false,
      
      // 连接重试策略
      retry: {
        maxAttempts: parseInt(process.env.DB_RETRY_ATTEMPTS) || 5,
        delay: parseInt(process.env.DB_RETRY_DELAY) || 2000,
        factor: parseFloat(process.env.DB_RETRY_FACTOR) || 2
      }
    },

    // Redis优化配置
    redis: {
      host: process.env.REDIS_HOST || 'localhost',
      port: parseInt(process.env.REDIS_PORT) || 6379,
      password: process.env.REDIS_PASSWORD || '',
      db: parseInt(process.env.REDIS_DB) || 0,
      keyPrefix: process.env.REDIS_KEY_PREFIX || 'bike:',
      
      // 连接池优化
      poolSize: parseInt(process.env.REDIS_POOL_SIZE) || 20,
      connectTimeout: parseInt(process.env.REDIS_CONNECT_TIMEOUT) || 10000,
      commandTimeout: parseInt(process.env.REDIS_COMMAND_TIMEOUT) || 5000,
      
      // 重连策略
      retryDelayOnFailover: parseInt(process.env.REDIS_RETRY_DELAY) || 100,
      maxRetriesPerRequest: parseInt(process.env.REDIS_MAX_RETRIES) || 3,
      
      // 集群配置
      cluster: process.env.REDIS_CLUSTER === 'true',
      nodes: process.env.REDIS_NODES ? 
        process.env.REDIS_NODES.split(',').map(node => {
          const [host, port] = node.split(':');
          return { host, port: parseInt(port) };
        }) : null
    },

    // MongoDB优化配置
    mongodb: {
      uri: process.env.MONGODB_URI || 'mongodb://localhost:27017/bike_community',
      db: process.env.MONGODB_DB || 'bike_community',
      
      // 连接池优化
      poolSize: parseInt(process.env.MONGODB_POOL_SIZE) || 50,
      minPoolSize: parseInt(process.env.MONGODB_MIN_POOL_SIZE) || 5,
      maxIdleTimeMS: parseInt(process.env.MONGODB_MAX_IDLE_TIME) || 30000,
      
      // 超时配置
      connectTimeoutMS: parseInt(process.env.MONGODB_CONNECT_TIMEOUT) || 10000,
      socketTimeoutMS: parseInt(process.env.MONGODB_SOCKET_TIMEOUT) || 45000,
      serverSelectionTimeoutMS: parseInt(process.env.MONGODB_SERVER_SELECTION_TIMEOUT) || 10000,
      
      // 读写偏好
      readPreference: process.env.MONGODB_READ_PREFERENCE || 'primaryPreferred',
      
      // 压缩
      compressors: process.env.MONGODB_COMPRESSORS ? 
        process.env.MONGODB_COMPRESSORS.split(',') : ['zlib'],
      zlibCompressionLevel: parseInt(process.env.MONGODB_ZLIB_LEVEL) || 6,
      
      // SSL配置
      ssl: process.env.MONGODB_SSL === 'true',
      sslCA: process.env.MONGODB_SSL_CA,
      sslCert: process.env.MONGODB_SSL_CERT,
      sslKey: process.env.MONGODB_SSL_KEY
    }
  },

  // 缓存优化配置
  cache: {
    // 默认TTL配置
    defaultTTL: parseInt(process.env.CACHE_DEFAULT_TTL) || 3600, // 1小时
    
    // 缓存策略
    strategies: {
      // 产品缓存
      product: {
        ttl: parseInt(process.env.CACHE_PRODUCT_TTL) || 1800, // 30分钟
        maxSize: parseInt(process.env.CACHE_PRODUCT_MAX_SIZE) || 1000
      },
      
      // 用户缓存
      user: {
        ttl: parseInt(process.env.CACHE_USER_TTL) || 7200, // 2小时
        maxSize: parseInt(process.env.CACHE_USER_MAX_SIZE) || 500
      },
      
      // 会话缓存
      session: {
        ttl: parseInt(process.env.CACHE_SESSION_TTL) || 86400, // 24小时
        maxSize: parseInt(process.env.CACHE_SESSION_MAX_SIZE) || 10000
      },
      
      // 统计缓存
      stats: {
        ttl: parseInt(process.env.CACHE_STATS_TTL) || 300, // 5分钟
        maxSize: parseInt(process.env.CACHE_STATS_MAX_SIZE) || 100
      }
    },
    
    // 缓存预热配置
    warmUp: {
      enabled: process.env.CACHE_WARMUP_ENABLED === 'true',
      schedule: process.env.CACHE_WARMUP_SCHEDULE || '0 4 * * *', // 每天4点
      items: process.env.CACHE_WARMUP_ITEMS ? 
        process.env.CACHE_WARMUP_ITEMS.split(',') : ['products', 'categories']
    }
  },

  // 查询优化配置
  query: {
    // 慢查询阈值
    slowQueryThreshold: parseInt(process.env.SLOW_QUERY_THRESHOLD) || 1000, // 1秒
    
    // 查询超时
    timeout: parseInt(process.env.QUERY_TIMEOUT) || 30000, // 30秒
    
    // 批量操作配置
    batch: {
      maxSize: parseInt(process.env.BATCH_MAX_SIZE) || 100,
      delay: parseInt(process.env.BATCH_DELAY) || 10 // 10ms
    },
    
    // 分页优化
    pagination: {
      maxPageSize: parseInt(process.env.MAX_PAGE_SIZE) || 100,
      defaultPageSize: parseInt(process.env.DEFAULT_PAGE_SIZE) || 20,
      cursorThreshold: parseInt(process.env.CURSOR_THRESHOLD) || 50 // 超过50页使用游标分页
    }
  },

  // 监控配置
  monitoring: {
    // 性能监控
    performance: {
      enabled: process.env.PERFORMANCE_MONITOR_ENABLED === 'true',
      interval: parseInt(process.env.PERFORMANCE_MONITOR_INTERVAL) || 30000, // 30秒
      retention: parseInt(process.env.PERFORMANCE_RETENTION_DAYS) || 7 // 7天
    },
    
    // 健康检查
    healthCheck: {
      enabled: process.env.HEALTH_CHECK_ENABLED === 'true',
      interval: parseInt(process.env.HEALTH_CHECK_INTERVAL) || 60000, // 1分钟
      timeout: parseInt(process.env.HEALTH_CHECK_TIMEOUT) || 5000 // 5秒
    },
    
    // 告警配置
    alerts: {
      enabled: process.env.ALERTS_ENABLED === 'true',
      slowQueryThreshold: parseInt(process.env.ALERT_SLOW_QUERY_THRESHOLD) || 2000, // 2秒
      connectionThreshold: parseInt(process.env.ALERT_CONNECTION_THRESHOLD) || 10,
      cacheHitRateThreshold: parseInt(process.env.ALERT_CACHE_HIT_RATE_THRESHOLD) || 50 // 50%
    }
  },

  // 安全配置
  security: {
    // 数据库安全
    database: {
      // 连接加密
      encryptConnections: process.env.ENCRYPT_CONNECTIONS === 'true',
      
      // 查询日志
      logQueries: process.env.LOG_QUERIES === 'true',
      logSlowQueries: process.env.LOG_SLOW_QUERIES === 'true',
      
      // 敏感数据屏蔽
      maskSensitiveData: process.env.MASK_SENSITIVE_DATA === 'true',
      sensitiveFields: process.env.SENSITIVE_FIELDS ? 
        process.env.SENSITIVE_FIELDS.split(',') : ['password', 'email', 'phone']
    }
  }
};

// 环境验证
function validateEnvironment() {
  const errors = [];
  
  // 生产环境验证
  if (config.app.environment === 'production') {
    const requiredVars = [
      'DB_HOST', 'DB_NAME', 'DB_USER', 'DB_PASSWORD',
      'JWT_SECRET'
    ];
    
    for (const envVar of requiredVars) {
      if (!process.env[envVar]) {
        errors.push(`生产环境缺少必需的环境变量: ${envVar}`);
      }
    }
    
    // 安全验证
    if (process.env.JWT_SECRET === 'your-super-secret-jwt-key-change-in-production') {
      errors.push('请修改默认的JWT密钥');
    }
    
    if (process.env.DB_PASSWORD === 'password') {
      errors.push('请修改默认的数据库密码');
    }
  }
  
  // 配置验证
  if (config.database.postgresql.maxConnections < config.database.postgresql.minConnections) {
    errors.push('最大连接数不能小于最小连接数');
  }
  
  if (config.query.pagination.maxPageSize < config.query.pagination.defaultPageSize) {
    errors.push('最大分页大小不能小于默认分页大小');
  }
  
  if (errors.length > 0) {
    console.warn('⚠️ 配置验证警告:');
    errors.forEach(error => console.warn(`  - ${error}`));
  }
  
  return errors.length === 0;
}

// 获取优化建议
function getOptimizationSuggestions() {
  const suggestions = [];
  
  if (config.app.environment === 'production') {
    if (!config.database.postgresql.ssl) {
      suggestions.push('生产环境建议启用SSL加密数据库连接');
    }
    
    if (config.database.redis.cluster === false) {
      suggestions.push('生产环境建议使用Redis集群提高可用性');
    }
    
    if (!config.monitoring.performance.enabled) {
      suggestions.push('生产环境建议启用性能监控');
    }
  }
  
  // 性能优化建议
  if (config.database.postgresql.maxConnections < 20) {
    suggestions.push('建议增加PostgreSQL最大连接数以提高并发性能');
  }
  
  if (config.cache.defaultTTL < 1800) {
    suggestions.push('建议增加缓存TTL以提高缓存命中率');
  }
  
  return suggestions;
}

// 初始化配置
validateEnvironment();
const optimizationSuggestions = getOptimizationSuggestions();

if (optimizationSuggestions.length > 0) {
  console.log('💡 数据库优化建议:');
  optimizationSuggestions.forEach(suggestion => console.log(`  - ${suggestion}`));
}

export default config;
export { validateEnvironment, getOptimizationSuggestions };